package com.gm.manager.module.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gm.manager.common.domian.PE;
import com.gm.manager.common.domian.RP;
import com.gm.manager.common.domian.RSD;
import com.gm.manager.common.entity.db.UserDaoEntity;
import com.gm.manager.common.exception.ParameterException;
import com.gm.manager.common.tools.LoginUtils;
import com.gm.manager.common.tools.UUIDTools;
import com.gm.manager.module.login.entity.LoginBack;
import com.gm.manager.module.login.mapper.UserMapper;
import com.gm.manager.module.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhuZhaoYang
 * @date 2021/8/7 14:21
 */
@Service
public class LoginServiceImpl implements LoginService {
    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public LoginBack login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (!captcha.equalsIgnoreCase(code)) {
            throw new ParameterException("验证码错误");
        }
        UserDaoEntity userDaoEntity = userMapper.selectOne(new QueryWrapper<UserDaoEntity>().eq("username", username).eq("password", LoginUtils.md5(password, username)));
        if (userDaoEntity == null) {
            throw new ParameterException("用户名或密码错误");
        }
        //生成token
        userDaoEntity.setToken(UUIDTools.getUUID());
        userMapper.updateById(userDaoEntity);
        return userMapper.getInfoById(userDaoEntity.getId());
    }

    @Override
    public LoginBack checkLogin(String token) {
        UserDaoEntity userDaoEntity = userMapper.selectOne(new QueryWrapper<UserDaoEntity>().eq("token", token));
        if (userDaoEntity == null) {
            throw new ParameterException("请先登录");
        }
        return userMapper.getInfoById(userDaoEntity.getId());
    }

    @Override
    public int logout(Integer id) {
        UserDaoEntity userDaoEntity = userMapper.selectById(id);
        if (userDaoEntity == null) {
            throw new ParameterException("请先登录");
        }
        return userMapper.delToken(id);
    }

    @Override
    public int updatePassword(String newPassword, Integer userId, String username) {
        //加盐加密
        String password = LoginUtils.md5(newPassword, username);
        return userMapper.updatePassword(password, userId);
    }
}
